package cn.vin.config.datasource;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Objects;

@Configuration
@MapperScan(basePackages = "cn.vin.dao.knife",sqlSessionTemplateRef = "knifeSqlSessionTemplate")
public class KnifeDatasourceConfig {

    @Bean(name = "knifeHikariConfig")
    @ConfigurationProperties(prefix = "knife.spring.datasource") // application.properteis中对应属性的前缀
    public HikariConfig knifeHikariConfig() {
        return new HikariConfig();
    }

    @Bean(name = "knifeDataSource")
    @Primary
    public DataSource knifeDataSource(@Qualifier("knifeHikariConfig")HikariConfig knifeHikariConfig) {
        HikariDataSource hikariDataSource = new HikariDataSource(knifeHikariConfig);
        return hikariDataSource;
    }

    @Bean(name = "knifeSqlSessionTemplate")
    public SqlSessionTemplate knifeSqlSessionTemplate(@Qualifier("knifeDataSource") DataSource knifeDataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(knifeDataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/knife/*.xml"));
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return new SqlSessionTemplate(Objects.requireNonNull(sqlSessionFactoryBean.getObject()));
    }

    @Bean(name = "knifeTransactionManager")
    public DataSourceTransactionManager knifeTransactionManager(@Qualifier("knifeDataSource")DataSource knifeDataSource) {
        return new DataSourceTransactionManager(knifeDataSource);
    }
}
